<?php
namespace app\api\controller;

use think\facade\Db;
use think\facade\Cache;

class ApiConData2
{
    public static function sendApi($data=array())
    {
        try {
            $user_id        = $data['user_id'] ?? 0;
            $host           = "https://purchasesapi.connexpay.com/api/v1";

            $action_type    = $data['action_type'];

            $method         = "POST";
            $code           = "";
            $result         = false;
            $card_num       = $data['card_num'] ?? "";
            $cardGuid       = $data['cardGuid'] ?? "";
            if($action_type == 'get_token'){
                $header         = [
                    "Content-Type: application/x-www-form-urlencoded"
                ];
            }else{
                $token          = self::getToken();
                $header         = [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $token
                ];
            }
            $request_data   = $data['request_data'] ?? "";
            if($action_type == 'get_token'){
                $host .= "/token";
                $request_data   = 'grant_type=password&username=ppttradingapi01&password=190F4VHzpCm1htP';
            } else if($action_type == 'addCard'){
                $host .= "/IssueCard/LodgedCard";
            } else if($action_type == 'getCardDetail'){
                $host .= "/Cards/{$cardGuid}/True";
                $method  = "GET";
            } else if($action_type == 'card_update' ||
                $action_type == 'card_active' ||
                $action_type == 'card_suspended' ||
                $action_type == 'add_card_balance' ||
                $action_type == 'deduct_card_balance' ||
                $action_type == 'del_up_card'
            ){
                $host .= "/IssueCard/LodgedCard/{$cardGuid}";
                $method  = "PUT";
            }else if($action_type == 'card_del')
            {
//                $host .= "/IssueCard/Cancel/{$cardGuid}";
//                $method  = "PUT";
                $host .= "/TerminateCard/{$cardGuid}";
            }else if($action_type == 'get_tran')
            {
                $host .= "/Cards/Transactions/{$cardGuid}";
                $method  = "GET";
            }else if($action_type == 'get_account_token')
            {
                $host .= "/Search/AvailableFunds/6423ae42-1628-4ca1-a5fb-830da34177de";
                $method  = "GET";
            }else if($action_type == 'get_new_bin')
            {
                $host .= "/IssueCard/GetActiveBins/6423ae42-1628-4ca1-a5fb-830da34177de";
                $method  = "GET";
            }
            $curl_array = [
                CURLOPT_URL => $host,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_HTTPHEADER => $header
            ];
            if($method == 'POST' || $method == 'PUT'){
                $curl_array += [
                    CURLOPT_POSTFIELDS => is_array($request_data)?json_encode($request_data):$request_data
                ];
            }
            $curl = curl_init();
            curl_setopt_array($curl, $curl_array);
            $response = curl_exec($curl);
            curl_close($curl);
            $list = '';
            if($response !== false){
                $response_array = json_decode($response , true);
                if(!isset($response_array['Log-Id'])){
                    if(!isset($response_array['message'])){
                        $code   = 200;
                        $list   = $response_array;
                        $result = true;
                        if($action_type == 'addCard'){
                            $card_num = $response_array['card']['accountNumber'] ?? '';
                        }
                    }else{
                        $list = $response_array['message'] ?? 'The request is invalid.';
                    }
                }
            }
            $insert_data = [
                'user_id' => $user_id,
                'name'    => $action_type,
                'url'     => $host,
                'card_num'=> $card_num,
                'ip'      => ip(),
                'method'  => $method,
                'header'  => json_encode($header),
                'request' => json_encode($request_data),
                'code'    => $code,
                'response'=> $response,
                'ctime'   => getUtcTime()
            ];
            if($action_type != 'get_card_detail'){
                //记录接口日志
                if($action_type == 'get_tran'){
                    $is_have = Db::name('lss_api_log')->where([
                        'card_num'=> $card_num,
                        'name'    => 'get_tran'
                    ])->select()->toArray();
                    if(count($is_have)>0){
                        Db::name('lss_api_log')->where([
                            'card_num'=> $card_num,
                            'name'    => 'get_tran'
                        ])->delete();
                    }
                }
                if($action_type = 'getCardDetail'){
                    $search_type = Db::name('lss_api_log')->where([
                        'name'=>'getCardDetail',
                        'card_num'=> $card_num,
                    ])->order('ctime desc')->find();
                    if($search_type){
                        $search_id = $search_type['id'];
                        Db::name('lss_api_log')->where([
                            'id'=>$search_id])->update([
                            'ip'      => ip(),
                            'response'=> $response,
                            'ctime'   => getUtcTime()
                        ]);
                    }
                }
                Db::name('lss_api_log')->save($insert_data);
                return [
                    'blog'      => $result,
                    'list'      => $list
                ];
            }
        }catch (\Exception $e){
            $err_msg = $e->getMessage();
            Db::name('api_error')->save([
                'user_id'       => 0,
                'amount'        => 0,
                'amount_bank'   => 0,
                'type'          => 'lss_' .$action_type,
                'data_param'    => is_array($err_msg) ? json_encode($err_msg) : $err_msg,
                'ctime'         => getUtcTime(),
                'is_rep'        => 1
            ]);
            return false;
        }
    }

    public static function getToken()
    {
        $bank_token_key = 'api_bank_token';
        $bank_token     = Cache::store('redis')->get($bank_token_key);

        $blog           = $bank_token;
        if(empty($bank_token)){
            $api_token = [
                "action_type"   => "get_token"
            ];
            $token_api= self::sendApi($api_token);
            $token_blog    = $token_api['blog'];
            $token_list    = $token_api['list'];
            if($token_blog){
                $bank_token = $token_list['access_token'];
                Cache::store('redis')->set($bank_token_key , $bank_token , 12*60*60);
                $blog = $bank_token;
            }
        }
        return $blog;
    }
}
